{% extends 'base.html' %}
{% load static %}

{% block title %}数据生成 - CFS Web System{% endblock %}

{% block page_type %}data-generation{% endblock %}

{% block breadcrumb_items %}
<li class="breadcrumb-item"><a href="{% url 'dashboard:dashboard' %}">仪表板</a></li>
<li class="breadcrumb-item active">数据生成</li>
{% endblock %}

{% block content %}
<div class="row">
    <!-- 页面标题 -->
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-magic me-2"></i>数据生成</h2>
            <div class="btn-group">
                <a href="{% url 'excel_processor:status' %}" class="btn btn-outline-primary">
                    <i class="fas fa-tasks"></i> 任务状态
                </a>
                <button type="button" class="btn btn-info" data-bs-toggle="modal" data-bs-target="#helpModal">
                    <i class="fas fa-question-circle"></i> 帮助
                </button>
            </div>
        </div>
    </div>
</div>

<form id="generation-form" method="POST">
    {% csrf_token %}
    
    <div class="row">
        <!-- 主要配置区域 -->
        <div class="col-lg-8">
            <!-- 步骤1: 选择模板 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">
                        <span class="step-number">1</span>
                        <i class="fas fa-file-alt me-2"></i>选择处理模板
                    </h5>
                </div>
                <div class="card-body">
                    {% if templates %}
                        <div class="row">
                            {% for template in templates %}
                            <div class="col-md-6 mb-3">
                                <div class="card template-option" data-template-id="{{ template.id }}">
                                    <div class="card-body">
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="template_id" 
                                                   id="template_{{ template.id }}" value="{{ template.id }}"
                                                   {% if request.GET.template_id == template.id|stringformat:'s' %}checked{% endif %}>
                                            <label class="form-check-label w-100" for="template_{{ template.id }}">
                                                <div class="d-flex justify-content-between align-items-start">
                                                    <div>
                                                        <h6 class="mb-1">{{ template.name }}</h6>
                                                        <p class="text-muted mb-2">{{ template.description|default:'暂无描述'|truncatechars:50 }}</p>
                                                        <small class="text-muted">
                                                            <i class="fas fa-calendar me-1"></i>{{ template.created_at|date:'Y-m-d' }}
                                                        </small>
                                                    </div>
                                                    <div class="text-end">
                                                        {% if template.is_active %}
                                                            <span class="badge bg-success">启用</span>
                                                        {% else %}
                                                            <span class="badge bg-secondary">禁用</span>
                                                        {% endif %}
                                                    </div>
                                                </div>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                    {% else %}
                        <div class="text-center py-4">
                            <i class="fas fa-file-alt fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">暂无可用模板</h5>
                            <p class="text-muted mb-3">请先创建处理模板才能进行数据生成。</p>
                            <a href="{% url 'template_management:template_create' %}" class="btn btn-primary">
                                <i class="fas fa-plus"></i> 创建模板
                            </a>
                        </div>
                    {% endif %}
                </div>
            </div>
            
            <!-- 步骤2: 选择源文件 -->
            <div class="card mb-4" id="file-selection-card" style="display: none;">
                <div class="card-header">
                    <h5 class="mb-0">
                        <span class="step-number">2</span>
                        <i class="fas fa-file-upload me-2"></i>选择源文件
                    </h5>
                </div>
                <div class="card-body">
                    <div id="file-list-container">
                        <!-- 文件列表将通过AJAX加载 -->
                    </div>
                </div>
            </div>
            
            <!-- 步骤3: 处理选项 -->
            <div class="card mb-4" id="options-card" style="display: none;">
                <div class="card-header">
                    <h5 class="mb-0">
                        <span class="step-number">3</span>
                        <i class="fas fa-cogs me-2"></i>处理选项
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <label for="task-name" class="form-label">任务名称</label>
                            <input type="text" class="form-control" id="task-name" name="task_name" 
                                   placeholder="输入任务名称" required>
                        </div>
                        <div class="col-md-6">
                            <label for="output-format" class="form-label">输出格式</label>
                            <select class="form-select" id="output-format" name="output_format">
                                <option value="xlsx">Excel (.xlsx)</option>
                                <option value="csv">CSV (.csv)</option>
                                <option value="both">两种格式</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label for="group-by" class="form-label">分组依据 (可选)</label>
                            <select class="form-select" id="group-by" name="group_by">
                                <option value="">不分组</option>
                                <!-- 选项将根据选择的模板动态加载 -->
                            </select>
                        </div>
                        <div class="col-md-6">
                            <div class="form-check mt-4">
                                <input class="form-check-input" type="checkbox" id="merge-sheets" name="merge_sheets">
                                <label class="form-check-label" for="merge-sheets">
                                    合并工作表
                                </label>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row mt-3">
                        <div class="col-12">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="include-summary" name="include_summary" checked>
                                <label class="form-check-label" for="include-summary">
                                    包含汇总信息
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="compress-output" name="compress_output" checked>
                                <label class="form-check-label" for="compress-output">
                                    压缩输出文件
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 提交按钮 -->
            <div class="text-center" id="submit-section" style="display: none;">
                <button type="submit" class="btn btn-success btn-lg" id="start-generation-btn">
                    <i class="fas fa-play me-2"></i>开始生成
                </button>
            </div>
        </div>
        
        <!-- 侧边栏信息 -->
        <div class="col-lg-4">
            <!-- 模板信息 -->
            <div class="card mb-4" id="template-info-card" style="display: none;">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-info-circle me-2"></i>模板信息
                    </h6>
                </div>
                <div class="card-body" id="template-info-content">
                    <!-- 模板信息将通过JavaScript动态加载 -->
                </div>
            </div>
            
            <!-- 文件信息 -->
            <div class="card mb-4" id="file-info-card" style="display: none;">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-file-alt me-2"></i>文件信息
                    </h6>
                </div>
                <div class="card-body" id="file-info-content">
                    <!-- 文件信息将通过JavaScript动态加载 -->
                </div>
            </div>
            
            <!-- 处理预览 -->
            <div class="card mb-4" id="preview-card" style="display: none;">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-eye me-2"></i>处理预览
                    </h6>
                </div>
                <div class="card-body" id="preview-content">
                    <!-- 预览信息将通过JavaScript动态加载 -->
                </div>
            </div>
            
            <!-- 最近任务 -->
            <div class="card">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-clock me-2"></i>最近任务
                    </h6>
                </div>
                <div class="card-body">
                    {% if recent_tasks %}
                        {% for task in recent_tasks %}
                        <div class="d-flex align-items-center mb-3">
                            <div class="flex-shrink-0">
                                <div class="status-badge status-{{ task.status }}"></div>
                            </div>
                            <div class="flex-grow-1 ms-3">
                                <h6 class="mb-0">{{ task.name|truncatechars:15 }}</h6>
                                <small class="text-muted">{{ task.created_at|timesince }}前</small>
                            </div>
                            <div class="flex-shrink-0">
                                {% if task.status == 'completed' %}
                                    <a href="/excel-processor/download/{{ task.id }}/" 
                                       class="btn btn-sm btn-outline-success">
                                        <i class="fas fa-download"></i>
                                    </a>
                                {% endif %}
                            </div>
                        </div>
                        {% endfor %}
                    {% else %}
                        <div class="text-center py-3">
                            <i class="fas fa-inbox fa-2x text-muted mb-2"></i>
                            <p class="text-muted mb-0">暂无最近任务</p>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</form>

<!-- 帮助模态框 -->
<div class="modal fade" id="helpModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-question-circle me-2"></i>数据生成帮助
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6><i class="fas fa-list-ol me-2"></i>操作步骤</h6>
                        <ol>
                            <li>选择要使用的处理模板</li>
                            <li>选择一个或多个源数据文件</li>
                            <li>配置处理选项和输出格式</li>
                            <li>点击"开始生成"启动处理任务</li>
                        </ol>
                        
                        <h6 class="mt-4"><i class="fas fa-cogs me-2"></i>处理选项说明</h6>
                        <ul>
                            <li><strong>任务名称:</strong> 用于标识和管理任务</li>
                            <li><strong>输出格式:</strong> 支持Excel、CSV或两种格式</li>
                            <li><strong>分组依据:</strong> 按指定列对数据进行分组</li>
                            <li><strong>合并工作表:</strong> 将多个工作表合并为一个</li>
                        </ul>
                    </div>
                    <div class="col-md-6">
                        <h6><i class="fas fa-lightbulb me-2"></i>使用技巧</h6>
                        <ul>
                            <li>建议为任务设置有意义的名称</li>
                            <li>大文件处理可能需要较长时间</li>
                            <li>可以在任务状态页面查看进度</li>
                            <li>处理完成后会自动生成下载链接</li>
                        </ul>
                        
                        <h6 class="mt-4"><i class="fas fa-exclamation-triangle me-2"></i>注意事项</h6>
                        <ul>
                            <li>确保源文件格式与模板匹配</li>
                            <li>处理过程中请勿关闭浏览器</li>
                            <li>大批量数据建议分批处理</li>
                            <li>定期清理已完成的任务</li>
                        </ul>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <a href="#" class="btn btn-primary">查看详细文档</a>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 模板数据
const templatesData = {
    {% for template in templates %}
    '{{ template.id }}': {
        id: '{{ template.id }}',
        name: '{{ template.name|escapejs }}',
        description: '{{ template.description|default:"暂无描述"|escapejs }}',
        is_active: {{ template.is_active|yesno:"true,false" }},
        created_at: '{{ template.created_at|date:"Y-m-d" }}',
        usage_count: {{ template.usage_count|default:0 }},
        config: {
            source_columns: {{ template.excel_structure|default:"[]"|safe }},
            target_columns: []
        }
    }{% if not forloop.last %},{% endif %}
    {% endfor %}
};

// 页面状态管理
const pageState = {
    selectedTemplate: null,
    selectedFiles: [],
    templateInfo: null
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeDataGeneration();
});

// 初始化数据生成页面
function initializeDataGeneration() {
    // 绑定模板选择事件
    const templateRadios = document.querySelectorAll('input[name="template_id"]');
    templateRadios.forEach(radio => {
        radio.addEventListener('change', function() {
            if (this.checked) {
                selectTemplate(this.value);
            }
        });
    });
    
    // 如果URL中有template_id参数，自动选择
    const urlParams = new URLSearchParams(window.location.search);
    const templateId = urlParams.get('template_id');
    if (templateId) {
        const radio = document.querySelector(`input[name="template_id"][value="${templateId}"]`);
        if (radio) {
            radio.checked = true;
            selectTemplate(templateId);
        }
    }
    
    // 绑定表单提交事件
    const form = document.getElementById('generation-form');
    if (form) {
        form.addEventListener('submit', handleFormSubmit);
    }
}

// 选择模板
function selectTemplate(templateId) {
    pageState.selectedTemplate = templateId;
    
    // 显示模板信息卡片
    document.getElementById('template-info-card').style.display = 'block';
    
    // 加载模板信息
    loadTemplateInfo(templateId);
    
    // 显示文件选择卡片
    document.getElementById('file-selection-card').style.display = 'block';
    
    // 加载文件列表
    loadFileList(templateId);
    
    // 滚动到文件选择区域
    document.getElementById('file-selection-card').scrollIntoView({ 
        behavior: 'smooth', 
        block: 'start' 
    });
}

// 加载模板信息
function loadTemplateInfo(templateId) {
    const container = document.getElementById('template-info-content');
    
    // 直接从templatesData获取模板信息
    const template = templatesData[templateId];
    if (template) {
        pageState.templateInfo = template;
        renderTemplateInfo(template);
        
        // 更新分组选项
        updateGroupByOptions(template.config);
    } else {
        container.innerHTML = '<div class="alert alert-danger">模板信息不存在</div>';
    }
}

// 渲染模板信息
function renderTemplateInfo(template) {
    const container = document.getElementById('template-info-content');
    
    const html = `
        <h6>${template.name}</h6>
        <p class="text-muted mb-3">${template.description || '暂无描述'}</p>
        
        <div class="row mb-2">
            <div class="col-6">
                <small class="text-muted">状态:</small><br>
                <span class="badge bg-${template.is_active ? 'success' : 'secondary'}">
                    ${template.is_active ? '启用' : '禁用'}
                </span>
            </div>
            <div class="col-6">
                <small class="text-muted">使用次数:</small><br>
                <span class="fw-bold">${template.usage_count || 0}</span>
            </div>
        </div>
        
        ${template.config ? `
            <div class="mt-3">
                <small class="text-muted">配置信息:</small><br>
                <span class="badge bg-info me-1">${template.config.source_columns ? template.config.source_columns.length : 0} 源列</span>
                <span class="badge bg-warning">${template.config.target_columns ? template.config.target_columns.length : 0} 目标列</span>
            </div>
        ` : ''}
    `;
    
    container.innerHTML = html;
}

// 加载文件列表
function loadFileList(templateId) {
    const container = document.getElementById('file-list-container');
    CFS.utils.showLoading(container, '加载文件列表...');
    
    const params = new URLSearchParams({
        file_type: 'source',
        template_id: templateId
    });
    
    fetch(`/file-manager/ajax/files/?${params.toString()}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderFileList(data.files);
            } else {
                container.innerHTML = '<div class="alert alert-danger">加载失败: ' + data.error + '</div>';
            }
        })
        .catch(error => {
            container.innerHTML = '<div class="alert alert-danger">加载失败: ' + error.message + '</div>';
        });
}

// 渲染文件列表
function renderFileList(files) {
    const container = document.getElementById('file-list-container');
    
    if (files.length === 0) {
        container.innerHTML = `
            <div class="text-center py-4">
                <i class="fas fa-file-upload fa-3x text-muted mb-3"></i>
                <h6 class="text-muted">请上传源数据文件</h6>
                
                <!-- Source Name Input -->
                <div class="mb-3">
                    <label for="source-name-input" class="form-label">数据源名称 (source_name)</label>
                    <input type="text" class="form-control" id="source-name-input" 
                           placeholder="请输入数据源名称，如：source" value="source">
                    <small class="form-text text-muted">此名称将用于模板中的数据源标识</small>
                </div>
                
                <!-- File Upload Area -->
                <div class="file-upload-area border-2 border-dashed border-primary rounded p-4 mb-3" 
                     id="direct-upload-area" style="cursor: pointer;">
                    <i class="fas fa-cloud-upload-alt fa-2x text-primary mb-2"></i>
                    <p class="mb-2">点击或拖拽文件到此处上传</p>
                    <p class="text-muted small">支持 Excel 文件 (.xlsx, .xls)</p>
                    <input type="file" id="direct-file-input" multiple accept=".xlsx,.xls" style="display: none;">
                </div>
                
                <!-- Upload Progress -->
                <div id="upload-progress" style="display: none;">
                    <div class="progress mb-2">
                        <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                    </div>
                    <small class="text-muted">正在上传...</small>
                </div>
            </div>
        `;
        return;
    }
    
    const html = files.map(file => `
        <div class="card mb-2 file-option" data-file-id="${file.id}">
            <div class="card-body p-3">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="source_files" 
                           id="file_${file.id}" value="${file.id}">
                    <label class="form-check-label w-100" for="file_${file.id}">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="mb-1">${file.original_name}</h6>
                                <small class="text-muted">
                                    ${file.file_type} | ${CFS.utils.formatFileSize(file.file_size)} | 
                                    ${CFS.utils.formatDateTime(file.created_at)}
                                </small>
                            </div>
                            <div>
                                <button type="button" class="btn btn-sm btn-outline-primary preview-file" 
                                        data-file-id="${file.id}">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                    </label>
                </div>
            </div>
        </div>
    `).join('');
    
    container.innerHTML = html;
    
    // 绑定文件选择事件
    const fileCheckboxes = container.querySelectorAll('input[name="source_files"]');
    fileCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            updateSelectedFiles();
        });
    });
    
    // 绑定预览按钮事件
    const previewButtons = container.querySelectorAll('.preview-file');
    previewButtons.forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            previewFile(this.dataset.fileId);
        });
    });
}

// 更新选中的文件
function updateSelectedFiles() {
    const checkboxes = document.querySelectorAll('input[name="source_files"]:checked');
    pageState.selectedFiles = Array.from(checkboxes).map(cb => cb.value);
    
    if (pageState.selectedFiles.length > 0) {
        // 显示处理选项卡片
        document.getElementById('options-card').style.display = 'block';
        document.getElementById('submit-section').style.display = 'block';
        
        // 显示文件信息
        document.getElementById('file-info-card').style.display = 'block';
        updateFileInfo();
        
        // 显示预览
        document.getElementById('preview-card').style.display = 'block';
        updatePreview();
        
        // 滚动到选项区域
        document.getElementById('options-card').scrollIntoView({ 
            behavior: 'smooth', 
            block: 'start' 
        });
    } else {
        // 隐藏后续步骤
        document.getElementById('options-card').style.display = 'none';
        document.getElementById('submit-section').style.display = 'none';
        document.getElementById('file-info-card').style.display = 'none';
        document.getElementById('preview-card').style.display = 'none';
    }
}

// 更新文件信息
function updateFileInfo() {
    const container = document.getElementById('file-info-content');
    const selectedCount = pageState.selectedFiles.length;
    
    container.innerHTML = `
        <div class="text-center">
            <h5 class="text-primary">${selectedCount}</h5>
            <small class="text-muted">已选择文件</small>
        </div>
        <hr>
        <small class="text-muted">文件将按照模板配置进行处理，生成相应的输出文件。</small>
    `;
}

// 更新预览
function updatePreview() {
    const container = document.getElementById('preview-content');
    const taskName = document.getElementById('task-name').value || '未命名任务';
    const outputFormat = document.getElementById('output-format').value;
    
    container.innerHTML = `
        <div class="mb-2">
            <small class="text-muted">任务名称:</small><br>
            <span class="fw-bold">${taskName}</span>
        </div>
        <div class="mb-2">
            <small class="text-muted">输出格式:</small><br>
            <span class="badge bg-info">${outputFormat.toUpperCase()}</span>
        </div>
        <div class="mb-2">
            <small class="text-muted">文件数量:</small><br>
            <span class="fw-bold">${pageState.selectedFiles.length}</span>
        </div>
    `;
}

// 更新分组选项
function updateGroupByOptions(config) {
    const select = document.getElementById('group-by');
    
    // 清空现有选项
    select.innerHTML = '<option value="">不分组</option>';
    
    if (config && config.source_columns) {
        config.source_columns.forEach(column => {
            const option = document.createElement('option');
            option.value = column.name;
            option.textContent = column.display_name || column.name;
            select.appendChild(option);
        });
    }
}

// 预览文件
function previewFile(fileId) {
    // 实现文件预览功能
    console.log('预览文件:', fileId);
}

// 处理表单提交
function handleFormSubmit(e) {
    e.preventDefault();
    
    // 验证表单
    if (!pageState.selectedTemplate) {
        CFS.utils.showNotification('请选择处理模板', 'warning');
        return;
    }
    
    if (pageState.selectedFiles.length === 0) {
        CFS.utils.showNotification('请选择源文件', 'warning');
        return;
    }
    
    const taskName = document.getElementById('task-name').value.trim();
    if (!taskName) {
        CFS.utils.showNotification('请输入任务名称', 'warning');
        return;
    }
    
    // 收集表单数据
    const formData = {
        template_id: pageState.selectedTemplate,
        source_files: pageState.selectedFiles,
        task_name: taskName,
        processing_options: {
            output_format: document.getElementById('output-format').value,
            group_by: document.getElementById('group-by').value,
            merge_sheets: document.getElementById('merge-sheets').checked,
            include_summary: document.getElementById('include-summary').checked,
            compress_output: document.getElementById('compress-output').checked
        }
    };
    
    // 显示加载状态
    const submitBtn = document.getElementById('start-generation-btn');
    const originalText = submitBtn.innerHTML;
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>正在提交...';
    
    // 提交请求
    fetch('/excel-processor/ajax/process/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': CFS.utils.getCsrfToken()
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
        
        if (data.success) {
            CFS.utils.showNotification('任务创建成功，正在处理中...', 'success');
            
            // 跳转到任务状态页面
            setTimeout(() => {
                window.location.href = `/excel-processor/status/?task_id=${data.task_id}`;
            }, 2000);
        } else {
            CFS.utils.showNotification('任务创建失败: ' + data.error, 'error');
        }
    })
    .catch(error => {
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
        CFS.utils.showNotification('提交失败: ' + error.message, 'error');
    });
}

// 直接文件上传处理
function setupDirectFileUpload() {
    const uploadArea = document.getElementById('direct-upload-area');
    const fileInput = document.getElementById('direct-file-input');
    const progressDiv = document.getElementById('upload-progress');
    const progressBar = progressDiv.querySelector('.progress-bar');
    
    if (!uploadArea || !fileInput) return;
    
    // 点击上传区域触发文件选择
    uploadArea.addEventListener('click', () => {
        fileInput.click();
    });
    
    // 拖拽上传
    uploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadArea.classList.add('dragover');
    });
    
    uploadArea.addEventListener('dragleave', (e) => {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
    });
    
    uploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
        const files = e.dataTransfer.files;
        handleDirectFileUpload(files);
    });
    
    // 文件选择处理
    fileInput.addEventListener('change', (e) => {
        handleDirectFileUpload(e.target.files);
    });
}

// 处理直接文件上传
function handleDirectFileUpload(files) {
    if (!files || files.length === 0) return;
    
    const sourceName = document.getElementById('source-name-input').value.trim();
    if (!sourceName) {
        CFS.utils.showNotification('请输入数据源名称', 'warning');
        return;
    }
    
    const progressDiv = document.getElementById('upload-progress');
    const progressBar = progressDiv.querySelector('.progress-bar');
    
    // 显示进度条
    progressDiv.style.display = 'block';
    progressBar.style.width = '0%';
    
    // 创建FormData
    const formData = new FormData();
    
    // 添加文件和配置
    Array.from(files).forEach((file, index) => {
        formData.append('files', file);
    });
    
    // 添加文件配置
    const fileConfigs = Array.from(files).map((file, index) => ({
        index: index,
        source_name: sourceName,
        file_type: 'source'
    }));
    
    formData.append('file_configs', JSON.stringify(fileConfigs));
    formData.append('template_id', pageState.selectedTemplate || '');
    formData.append('description', `数据处理任务 - ${sourceName}`);
    
    // 上传文件
    fetch('/data-processing/api/tasks/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        progressDiv.style.display = 'none';
        
        if (data.message) {
            CFS.utils.showNotification('文件上传成功', 'success');
            // 重新加载文件列表
            loadFiles();
        } else {
            CFS.utils.showNotification('上传失败: ' + (data.error || '未知错误'), 'error');
        }
    })
    .catch(error => {
        progressDiv.style.display = 'none';
        CFS.utils.showNotification('上传失败: ' + error.message, 'error');
    });
}

// 监听任务名称变化，更新预览
document.addEventListener('DOMContentLoaded', function() {
    const taskNameInput = document.getElementById('task-name');
    if (taskNameInput) {
        taskNameInput.addEventListener('input', function() {
            if (pageState.selectedFiles.length > 0) {
                updatePreview();
            }
        });
    }
    
    // 设置直接文件上传
    setupDirectFileUpload();
});

// 修改loadFiles函数，当没有文件时显示上传界面
const originalLoadFiles = loadFiles;
loadFiles = function() {
    fetch('/core/api/files/')
    .then(response => response.json())
    .then(data => {
        if (data.files && data.files.length > 0) {
            renderFileList(data.files);
        } else {
            // 显示上传界面
            renderFileList([]);
        }
    })
    .catch(error => {
        console.error('加载文件列表失败:', error);
        renderFileList([]);
    });
};
</script>
{% endblock %}